package com.xrf;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class AESUtils {
    
    /***默认向量常量**/
    public static final String IV = "EkpTEA3FbZFGGq8Y";
    public static final String KEY = "G9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvM3";
    
    private final static Logger logger = LoggerFactory.getLogger(AESUtils.class);

    /**
     * AES加密
     */
    public static byte[] aesEncrypt(String content) {
        try {
            byte[] raw = KEY.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(content.getBytes());
            return encrypted;
        } catch (Exception e) {
            logger.info("aesEncrypt() method error:", e);
        }
        return null;
    }

    /**
     * AES加密字符串
     */
    public static String aesEncryptStr(String content) {
        byte[] aesEncrypt = aesEncrypt(content);
        String ss = new String(aesEncrypt, StandardCharsets.UTF_8);
        return ss;
    }

    /**
     * AES解密字符串
     */
    public static String aesDecodeStr(String content) throws Exception {
        try {
            byte[] base64DecodeStr = Base64.decodeBase64(content);
            System.out.println("base64DecodeStr:" + Arrays.toString(base64DecodeStr));
            String aesDecode = aesDecode(base64DecodeStr);
            System.out.println("aesDecode result:" + aesDecode);
            return aesDecode;
        } catch (Exception e) {
            System.out.println("Exception:" + e.getMessage());
            throw e;
        }
    }

    /**
     * AES解密
     */
    public static String aesDecode(byte[] content) throws Exception {
        byte[] raw = KEY.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] encrypted1 = new Base64().decode(content);
        try {
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        // 测试代码
    }
}